/*
 *  src/process_control/msg_queue.c
 *
 *  Harry Wei <harryxiyou@gmail.com> (C) 2011
 */
#include "process_control.h"

int client(void)
{
	key_t key;
	pid_t cli_pid;
	int mid;
	int n;
	MESSAGE msg;
	static char m_key[10];
	
	cli_pid = getpid();
	if (-1 == (key = ftok(".", SEED))) {
		g_message("%s -- ftok error!", __func__);
		return -1;
	}
	if (-1 == (mid = msgget(key, 0))) {
		if (-1 == (mid = msgget(key, IPC_CREAT | 0660))) {
			g_message("%s -- msgget error!", __func__);
			return -1;
		}
		switch (fork()) {
		case -1:
			g_message("%s -- fork error!", __func__);
			return -1;
		case 0:
			sprintf(m_key, "%d", mid);
			if (-1 == execlp("server", "server", m_key, "&", (char *) 0)) {
				g_message("%s -- execlp error!", __func__);
				exit(EXIT_FAILURE);
			}
			g_message("%s -- executed ...", __func__);
			exit(EXIT_SUCCESS);
		}
	}
	while (1) {
		msg.msg_to = SERVER;
		msg.msg_fm = cli_pid;
		write(fileno(stdout), "cmd>", 6);
		memset(msg.buffer, 0x0, BUFSIZ);
		n = read(fileno(stdin), msg.buffer, BUFSIZ);
		if (0 == n) {
			break;
		}
		if (-1 == msgsnd(mid, &msg, sizeof(msg), 0)) {
			g_message("%s -- %d msgsnd error!", __func__, __LINE__);
			return -1;
		}
		if (-1 == (n == msgrcv(mid, &msg, sizeof(msg), cli_pid, 0))) {
			g_message("%s -- msgrcv error!", __func__);
			return -1;
		}
		write(fileno(stdout), msg.buffer, strlen(msg.buffer));
	}
	if (-1 == msgsnd(mid, &msg, 0, 0)) {
		g_message("%s -- %d msgsnd error!", __func__, __LINE__);
		return -1;
	}
	return 0;
}

static void process_msg(char *b, int len)
{
	int i;

	for (i = 0; i < len; i++) {
		if (isalpha(*(b + i))) {
			*(b + i) = toupper(*(b + i));
		}
	}
	return ;
}

int server(int argc, char *argv[])
{
	int mid;
	int n;
	MESSAGE msg;

	if (3 != argc) {
		g_message("%s -- para error!", __func__);
		return -1;
	}
	mid = atoi(argv[1]);
	while (1) {
		if (-1 == (n = msgrcv(mid, &msg, sizeof(msg), SERVER, 0))) {
			g_message("%s -- msgrcv error!", __func__);
			return -1;
		} else if (0 == n) {
			break;
		} else {
			process_msg(msg.buffer, strlen(msg.buffer));
			msg.msg_to = msg.msg_fm;
			msg.msg_fm = SERVER;
			if (-1 == msgsnd(mid, &msg, sizeof(msg), 0)) {
				g_message("%s -- msgsnd error!", __func__);
				return -1;
			}
		}
	}
	if (-1 == msgctl(mid, IPC_RMID, (struct msqid_ds *) 0)) {
		g_message("%s -- msgctl error!", __func__);
		return -1;
	}
	exit(EXIT_SUCCESS);
}
